<template>
  <div>
    <p v-if='isReadOnlyPage === true'>{{strValue}}</p>
    <a-checkbox-group v-else :value="selected" :options="plainOptions" @change="onchange" :disabled="isDisabled" />
  </div>
</template>
<script>
export default {
  name: 'Checkbox',
  model: {
    prop: 'value',
    event: 'change'
  },
  props: ['value', 'values', 'isReadOnlyPage', 'isDisabled', 'isResume'],
  data () {
    return {
      plainOptions: []
    }
  },
  watch: {
    isDisabled: {
      handler (newVal) {
        console.log(newVal)
      },
      immediate: true,
      deep: true
    }
  },
  computed: {
    strValue () {
      let newStr = ''
      if (this.value) {
        if (this.value instanceof Array) {
          let val = []
          this.value.forEach(item => {
            if (item.id) {
              val.push(this.nameById(item.id))
            } else {
              val.push(this.nameById(item))
            }
          })
          newStr = val.join(',')
        } else {
          newStr = this.value
        }
      }
      return newStr
    },
    selected () {
      let newArr = []
      if (this.value) {
        if (this.value instanceof Array) {
          let val = []
          this.value.forEach(item => {
            if (item.id) {
              val.push(item.id)
            } else {
              val.push(item)
            }
          })
          newArr = val
        } else {
          newArr = this.value
        }
      }
      return newArr
    }
  },
  mounted () {
    if (!this.values) {
      return
    }
    console.log(this.values, '------------------------')
    this.values.forEach(element => {
      this.plainOptions.push({
        label: element.name,
        value: element.id
      })
    })
    // this.plainOptions = this.values
  },
  methods: {
    onchange (e) {
      let val = []
      e.forEach(item => {
        val.push({ id: item, name: this.nameById(item) })
      })
      // console.log('Checkbox', val)
      if (this.isResume) {
        this.$emit('change', e)
      } else {
        this.$emit('change', val)
      }
      this.$emit('onBlurFn', true)
    },
    nameById (id) {
      let item = this.plainOptions.find(item => {
        if (item.value === id) {
          return true
        }
        return false
      })
      if (item) {
        console.log('item', item)
        return item.label
      }
      return ''
    }
  }
}
</script>
<style lang="stylus" scoped>
</style>
